package manage.actions.example;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import manage.actions.ManageAction;
import manage.modules.upload.model.MultiFile;
import manage.modules.upload.model.SingleFile;
import manage.modules.upload.service.UploadFileService;

import org.apache.struts2.convention.annotation.Action;

public class UploadAction extends ManageAction {
	private static final long serialVersionUID = 6065730018268861212L;
	private MultiFile multiFile;
	private String state = "ERROR";
	private long MINSIZE = 0l;
	private long MAXSIZE = 50000000;
	private UploadFileService uploadFileService;

	@Action(value = "file-upload")
	public String uploadPhoto() throws Exception {
		if (multiFile != null) {
			File[] files = multiFile.getUpload();
			String[] uploadFileNames = multiFile.getUploadFileName();
			String[] uploadContentTypes = multiFile.getUploadContentType();
			StringBuilder subBuilder = new StringBuilder(1024);
			for (int i = 0; files != null && i < files.length; i++) {
				File file = files[i];
				String fileName = uploadFileNames[i];
				String contentType = uploadContentTypes[i];
				List<String> imgFormat = initImgFormat();
				if (!file.exists()) {
					state = "照片" + (i + 1) + ":找不到。请检查输入的照片是否在本机存在？<br/>";
					subBuilder.append(state);
					continue;
				}
				if (file.length() < MINSIZE) {
					state = "照片" + (i + 1) + ":小于10K，请重新选择！<br/>";
					subBuilder.append(state);
					continue;
				}
				if (file.length() > MAXSIZE) {
					state = "照片" + (i + 1) + ":超过4M，请重新选择！<br/>";
					subBuilder.append(state);
					continue;
				}
				if (contentType == null) {
					state = "照片" + (i + 1) + ":类型不能正确解析！<br/>";
					subBuilder.append(state);
					continue;
				}
				int lastIndex = fileName.lastIndexOf(".");
				String ext = "";
				if (lastIndex >= 0) {
					ext = fileName.substring(lastIndex);
				}
				boolean contains = imgFormat.contains(ext);
				if (!contains) {
					state = "照片" + (i + 1)
							+ "：格式不符合我们的上传标准，请选择BMP，JPG，PNG或GIF格式的照片！<br/>";
					subBuilder.append(state);
					continue;
				}
				uploadFileService.upload(new SingleFile(file, ext),
						currentWorker.getWorkerId());
			}
			if (subBuilder.length() > 0) {
				request.setAttribute("uploadedMsg", subBuilder.toString());
			}
		}
		return SUCCESS;
	}

	private List<String> initImgFormat() {
		String[] imgFormat = { ".jpg", ".png", ".gif", ".bmp", ".JPG", ".PNG",
				".GIF", ".BMP" };
		return Arrays.asList(imgFormat);
	}

	public String getState() {
		return state;
	}

	public void setMultiFile(MultiFile multiFile) {
		this.multiFile = multiFile;
	}

	public void setUploadFileService(UploadFileService uploadFileService) {
		this.uploadFileService = uploadFileService;
	}

	public MultiFile getMultiFile() {
		return multiFile;
	}

}
